package com.gzucm.Scholarship.service;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.gzucm.Scholarship.config.yml.S3Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

@Slf4j
@Service
public class S3FileService implements FileService {

    @Autowired
    private S3Config config;

    @Autowired
    private AmazonS3 amazonS3;

    @Override
    public boolean upload(String objectName, File file) {
        try {
            String bucketName = config.getBucketName();
            if (!amazonS3.doesBucketExistV2(bucketName)) {
                amazonS3.createBucket(bucketName);
            }
            amazonS3.putObject(new PutObjectRequest(bucketName, objectName, file));
            return true;
        } catch (Exception ase) {
            log.error("amazonS3上传文件File模式异常 " + ase.getMessage(), ase);
        }
        return false;
    }

    @Override
    public boolean download(String objectName, String path) {
        try {
            String bucketName = config.getBucketName();
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            amazonS3.getObject(request, new File(path));
            return true;
        } catch (Exception ase) {
            log.error("amazonS3下载文件异常 " + ase.getMessage(), ase);
        }
        return false;
    }

    @Override
    public boolean deleteFile(String objectName) {
        try {
            String bucketName = config.getBucketName();
            amazonS3.deleteObject(bucketName, objectName);
            return true;
        } catch (Exception ase) {
            log.error("amazonS3删除文件异常 " + ase.getMessage(), ase);
            return false;
        }
    }

    @Override
    public boolean isExist(String objectName) {
        String bucketName = config.getBucketName();
        return amazonS3.doesObjectExist(bucketName, objectName);
    }
}
